package com.youlu.campus.service.douyin;

import com.youlu.campus.common.utils.IdGeneratorUtils;
import com.youlu.campus.entity.ActivityInfo;
import com.youlu.campus.entity.ActivityTaskInfo;
import com.youlu.campus.entity.UserPO;
import com.youlu.campus.entity.WechatACode;
import com.youlu.campus.entity.enums.TaskBizType;
import com.youlu.campus.service.activity.ActivityService;
import com.youlu.campus.service.activity.ActivityTaskService;
import com.youlu.campus.service.file.FileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 获取抖音分享码
 */
@Slf4j
@Service
public class DouYinShareCodeService {


    @Value("${spring.profiles.active}")
    private String active;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private ActivityTaskService activityTaskService;

    @Autowired
    private ActivityService activityService;

    @Autowired
    private FileService fileService;


    @Autowired
    private DouYinApiService douYinApiService;


    /**
     * 抖音小程序分享路径
     */
    private final String PATH = "/pages/detail?sharedByOpenId=%s&taskId=%s&activityId=%s&sharedByUserId=%s" +
            "&activityType=%s";

    private final String APP_NAME = "douyin";


    public String getShareWxaCode(UserPO currentUser, String activityId) {
        log.info("【获取抖音小程序码】DouYInShareCodeService.getShareWxaCode userId ->{}|activityId->{}", currentUser.getId(), activityId);
        ActivityTaskInfo activityTaskInfo = activityTaskService.find(activityId, TaskBizType.INVITE);
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(currentUser.getId()));
        query.addCriteria(Criteria.where("activityId").is(activityId));
        WechatACode wechatACode = this.mongoTemplate.findOne(query, WechatACode.class);
        if (Objects.nonNull(wechatACode)) {
            return wechatACode.getWxaCode();
        }
        ActivityInfo activityInfo = activityService.findOne(activityId);
        String accessToken = douYinApiService.getAccessToken(douYinApiService.APP_ID);
        String sceneId = new ObjectId().toString();
        String path = String.format(PATH, currentUser.getOpenId(),activityTaskInfo.getId(),activityId,
                currentUser.getId(),activityInfo.getType());
        byte[] imageBytes = douYinApiService.getQrcodeBytes(accessToken, path, APP_NAME);
        if(ArrayUtils.isEmpty(imageBytes)){
            log.error("【获取抖音小程序码】DouYInShareCodeService.getShareWxaCode activityId:{} 错误",activityId);
            return "";
        }
        InputStream inputStream = null;
        try {
             inputStream = new ByteArrayInputStream(imageBytes);
            log.info("【获取抖音小程序码】DouYInShareCodeService.getShareWxaCode start 上传到七牛云");
            String fileName = "douyin-wxacode" + IdGeneratorUtils.generateId() + ".png";
            String imageUrl = fileService.uploadFile(inputStream, fileName);
            if (StringUtils.isBlank(imageUrl)) {
                log.error("【获取抖音小程序码】DouYInShareCodeService.getShareWxaCode activityId:{} 上传到七牛云错误",activityId);
                return "";
            }
            log.info("【获取抖音小程序码】DouYInShareCodeService.getShareWxaCode end url:{} 上传到七牛云",imageUrl);
            Date now = new Date();
            WechatACode saveWACode = new WechatACode();
            saveWACode.setId(sceneId);
            saveWACode.setActivityId(activityId);
            saveWACode.setActivityType(activityInfo.getType());
            saveWACode.setTaskId(activityTaskInfo.getId());
            saveWACode.setUserId(currentUser.getId());
            saveWACode.setSharedByOpenId(currentUser.getOpenId());
            saveWACode.setSharedByUserId(currentUser.getId());
            saveWACode.setWxaCode(imageUrl);
            saveWACode.setCreatedTime(now);
            saveWACode.setUpdatedTime(now);
            this.mongoTemplate.save(saveWACode);
            return imageUrl;
        }catch (Exception e){
            log.error("【分享抖音小程序码】DouYInShareCodeService.getShareWxaCode activityId:{} 错误",activityId,e);
            return "";
        }finally {
            if(Objects.nonNull(inputStream)){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
